import pandas as pd
import json
import numpy as np

from django.core.management.base import BaseCommand
from htstool.models import *


class Command(BaseCommand):

	def handle(self, *args, **options):
		# [u'Barcode', u'Well', u'Signal']
		content=pd.read_csv('lisa-cell-via-data.csv', usecols=[1,2,4])
		chunks=np.array_split(content, 18)

		pgroup=PlateGroup(groupname='cell viability plates raw readout', platecommonattr=['condition'])
		
		for df in chunks:

			onerow_df=pd.DataFrame({df['Barcode'].tolist()[0]:df['Signal'].values}, index=df['Well'].values).T
			rawdata=convert_to_df(onerow_df)


			df_dict=json.loads(rawdata.to_json())
			dataset=Dataset(data=df_dict)
			dataset.save()

			rawplate=RawPlate(platename=onerow_df.index[0], cellline='Awesome cell line X',
					condition='cell viability', concentration=999, dimension=[8,12], 
					replicate=int(onerow_df.index[0][-1]), data=dataset)
			rawplate.save()

			pgroup.plates.append(rawplate)

		pgroup.platecommonattr={'condition':'cell viability', 'dimension':df.shape}
		pgroup.save()

		exp=Experiment(expname='Lisa Cooper Assay', group='Lisa Cooper', screen='screen 1',
				library='Kinome library', description='blabla', 
				plategroups=[pgroup])

		exp.save()


def convert_to_df(rawdf):
	rows={}
	for label in rawdf.columns:
		val=rawdf[label].tolist()[0]
		if label[0] not in rows:
			rows[label[0]]=[]
		rows[label[0]].append(val)
		
	df=pd.DataFrame(rows)
	ind=['0'+str(n+1) if n < 9 else str(n+1) for n in df.index]
	df.index=ind
	return df.T

